package com.pengtu.gsj.service.impl.system;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pengtu.gsj.dao.check.CheckTableDao;
import com.pengtu.gsj.dao.system.SystemMenuDao;
import com.pengtu.gsj.entity.CheckMenusVo;
import com.pengtu.gsj.entity.CheckResultVo;
import com.pengtu.gsj.entity.CheckTableMenusVo;
import com.pengtu.gsj.entity.app.Sysmenu;
import com.pengtu.gsj.entity.check.CheckTable;
import com.pengtu.gsj.service.system.SysmenuManagerService;
import com.pengtu.gsj.utils.Constants;
import com.pengtu.gsj.utils.MathsUtils;

/** 
 * @author zl 
 * @version 创建时间：2017年4月1日 下午5:21:05 
 * 类说明 
 */
@Service
@Transactional
public class SysmenuManagerServiceImpl implements SysmenuManagerService {

	@Autowired
	private SystemMenuDao systemMenuDao;
	
	@Autowired
	private CheckTableDao checkTableDao;
	
	
	@Transactional(readOnly=true)
	@Override
	public List<Sysmenu> getAll() {
		return systemMenuDao.getAll("sort", true);
	}

	@Override
	public List<Sysmenu> findByUserId(String id) {
		return systemMenuDao.findByUserId(id);
	}

	@Override
	public Sysmenu get(String id) {
		return systemMenuDao.get(id);
	}

	@Override
	public void save(Sysmenu entity) {
		systemMenuDao.save(entity);
	}

	@Override
	public void delete(String id) {
		systemMenuDao.delete(id);
	}

	@Override
	public Sysmenu getTopMenu() {
		return systemMenuDao.findTopMenu();
	}

	@Override
	public List<Sysmenu> getByParentIds(String id) {
		return systemMenuDao.findByParentIds(id);
	}

	@Override
	public boolean isTagUnique(String newTag, String oldTag) {
		return systemMenuDao.isPropertyUnique("tag", newTag, oldTag);
	}

	@Override
	public Sysmenu findSysmenuByTag(String tag) {
		return systemMenuDao.findUniqueBy("tag", tag);
	}

	@Override
	public String getParentNames(Sysmenu sysmenu) {
		StringBuffer names = new StringBuffer();
		if (!"0".equals(sysmenu.getParent().getParentIds())) {
			String name = getParentNames(sysmenu.getParent());
			names.append(name);
			names.append(sysmenu.getParent().getName()).append(Constants.FILE_SEP);
		}
		return names.toString();
	}

	/**
	 * getLeastMenu:
	 * 适用:使用两级菜单的情况(装饰器左侧为准)
	 * @return 
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Deprecated
	@Override
	public Map<String, Sysmenu> getLeastMenu(String parentId, String start,
			Map<String, Sysmenu> map, Integer length) {
		if (map.size() == 0) {
			// 获取末级菜单ParentIds
			String maxParentIds =  systemMenuDao.getMaxParentIds(parentId);
			String[] arrParentIds = maxParentIds.split(",");
			// 父级菜单的个数
			length = arrParentIds.length;
		}
		String parentIds = systemMenuDao.getParentIds(parentId);
		String[] arrNow = parentIds.split(",");
		// 获取子集菜单
		List<Sysmenu> childMenus = systemMenuDao.getSysmenusByParentId(parentId);
		if (arrNow.length == length - 1) {// 跳出条件
			return map;
		} else {
			// 显示是第几级菜单
			Integer m = Integer.valueOf(start);
			// 再次进入下面循环则
			m++;
			if (map.size() != 0) {
				m = m - 1;
			}
			for (int i = 0; i < childMenus.size(); i++) {
				map.put(m + "" + i, childMenus.get(i));
				String id = childMenus.get(i).getId();
				getLeastMenu(id, m + "" + (i), map, length);
			}
		}
		return map;
	}

	/**
	 * getAllSysmenus:
	 * 适用:获得所有的系统菜单    菜单分类根据system区分  0 系统菜单  1 日常监管菜单
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public List<Sysmenu> getAllSysmenus() {
		return systemMenuDao.findBy("system", "0");
	}
	
	/**
	 * getRoadSysmenus:
	 * 适用:获得所有的日常监管菜单    菜单分类根据system区分  0 系统菜单  1 日常监管菜单
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public List<Sysmenu> getRoadSysmenus() {
		return systemMenuDao.findBy("system", "1");
	}
	
	
	/**
	 * getParentMenusById:
	 * 适用:返回叶子菜单的所有父级带单
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public List<Sysmenu> getParentMenusById(String id){
		List<Sysmenu> sysList= new ArrayList<Sysmenu>();
		//根据id获取当前菜单对象
		if(id != null){
			Sysmenu sysmenu = this.get(id);
			//获取父级菜单的长度，确定菜单的级数
			String parentIds = sysmenu.getParentIds();
			if(parentIds != null){
				String[] parIds = parentIds.substring(0,parentIds.length()-1).split(",");
				Sysmenu menu;
				//去除首页和第一级父菜单
				if(parIds.length > 2){
					for (int i = 2; i < parIds.length; i++) {
						menu = new Sysmenu();
						String pId = parIds[i];
						//System.out.println("序号："+i+" pId:"+pId);
						menu = systemMenuDao.findById(pId);
						sysList.add(menu);
					}
				}
			}
			sysList.add(sysmenu);
		}
		return sysList;
	}

	@Override
	public List<Sysmenu> getByParentId(String id) {
		return systemMenuDao.getSysmenusByParentId(id);
	}

	/**
	 * getcheckSysmenus:
	 * 适用:获得日常监管菜单中的业务模块菜单（即非叶子节点），便于在国省检的检查内容中选择
	 * 日常监管菜单中再细分菜单分类： menuType ：0  业务模块菜单   1 文件数据菜单
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public List<Sysmenu> getcheckSysmenus() {
		return systemMenuDao.findBy("menuType", "0");
	}
	/**
	 * getTableList:
	 * 适用:根据用户选中模块,对表格进行加载
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Deprecated
	@Override
	public List<Map<String, Object>> getTableList(String menuIds, String projId) {
		String tempId = "402880f65b8f1cea015b8f24ae3d0001";
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> tableMap = null;
		Map<String, Object> checkMap = null;
		if (StringUtils.isNotBlank(menuIds)) {
			tableMap = new HashMap<String, Object>();
			checkMap = new HashMap<String, Object>();
			String[] ids = menuIds.split(",");
			int j=-1;
			int w,x,y;
			for (w=0; w<ids.length; w++) {
				Sysmenu sysmenu = systemMenuDao.get(ids[w]);
				if (tempId.equals(sysmenu.getParent().getId())) {
					//除去当前已经匹配到的菜单,同事循环下标前移一位
					ids = this.arrContrast(ids, ids[w]);
					w -= 1;
					j++;
					// 获取一级菜单(也就是tabl切换)
					tableMap.put(1 + "" + j, sysmenu);
					
					//获取到一级菜单下全部的菜单，计算完善度
					List<CheckTable> tableList = checkTableDao.getSumSystems(sysmenu.getId(), projId);
					for (CheckTable checkTable : tableList) {
						checkMap.put(1+""+j, checkTable);
					}
				}
			}
			if (tableMap.size() > 0) {
				list.add(tableMap);
				list.add(checkMap);
				Map<String, Object> firstMap = new HashMap<String, Object>();
				boolean flag = false;
				for (String key : tableMap.keySet()) {
					// 通过key获取value
					Sysmenu sysmenu =(Sysmenu) tableMap.get(key);
					int z = -1;
					for (x = 0; x < ids.length; x++) {
						Sysmenu menu = systemMenuDao.get(ids[x]);
						if (sysmenu.getId().equals(menu.getParent().getId())) {
							ids = this.arrContrast(ids, ids[x]);
							x -= 1;
							z++;
							// 获取二级菜单(也就是表格前一行)
							firstMap.put(key + "" + z, menu);
							flag = true;
						}
					}
				}
				double sumTableFull = 0;
				double sumTestFull = 0;
				if (flag) {
					list.add(firstMap);
					Map<String, Object> secondMap = new HashMap<String, Object>();
					Map<String, Object> thirdMap = new HashMap<String, Object>();
					for (String specialKey : firstMap.keySet()) {
							boolean havaThirdMenu = false;
							Sysmenu m = (Sysmenu)firstMap.get(specialKey);
							for (y = 0; y < ids.length; y++) {
								Sysmenu mu = systemMenuDao.get(ids[y]);
								//判断是否存在三级菜单
								if (m.getId().equals(mu.getParent().getId())) {
									CheckTable checkTable = checkTableDao.findCheckTable(mu.getId(), projId);
									thirdMap.put(specialKey + "" + y, checkTable);
									secondMap.put(specialKey + "" + y, mu);
									flag = false;
									havaThirdMenu = true;
								}
							}
							//如果没有三级菜单，查询二级菜单的评分情况
							int z = -1;
							if (!havaThirdMenu) {
								z++;
								CheckTable checkTable = checkTableDao.findCheckTable(m.getId(), projId);
								thirdMap.put(specialKey + "" + z, checkTable);
							}
					}
					list.add(secondMap);
					list.add(thirdMap);
					
					for (String thirdKey :thirdMap.keySet()) {
						CheckTable checkTable = (CheckTable)thirdMap.get(thirdKey);
						if (checkTable != null) {
							sumTableFull += checkTable.getTableFull() != null ? checkTable.getTableFull() : 0;
							sumTestFull += checkTable.getTestFull() != null ? checkTable.getTestFull() : 0;
						}
					}
					
				}
				
				//返回总体评分
				Map<String, Object> overMap = new HashMap<String, Object>();
				overMap.put("zt", MathsUtils.formatDouble(sumTestFull/sumTableFull*100, 2));
				list.add(overMap);
			}
		}
		return list;
	}
	/**
	 * 
	 * getIdStrByParentId:
	 * 适用:得到某个父id下所有子模块的id集合
	 * @param id
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public List<String> getIdStrByParentId(String id) {
		return systemMenuDao.getIdStrByParentId(id);
	}

	@Override
	public List<String> getMenuByParentIds(String id) {
		return systemMenuDao.getMenuByParentIds(id);
	}
	
	/**
	 * 
	 * getCheckModule:
	 * 适用:获取某个国省检项目下检查的模块
	 * @param projectId 项目id
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public  List<Sysmenu> getCheckModule(String projectId) {
		return systemMenuDao.getCheckModule(projectId);
	}

	/**
	 * 
	 * getCheckResultVoByParentId:
	 * 适用:获取某个模块下检查表的总分和完善度
	 * @param projectId 项目id
	 * @param parentId 模块的id
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public List<CheckResultVo> getCheckResultVoByParentId(String projectId,
			String parentId) {
		return systemMenuDao.getCheckResultVoByParentId(projectId, parentId);
	}
	
	/**
	 * 
	 * arrContrast:
	 * 适用:数组去除某个元素
	 * @param arr[] 菜单id集合
	 * @param obj 所需要除去的id元素。
 	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	@Override
	public String[] arrContrast(String[] arr,String obj){
        List<String> list = new LinkedList<String>();
        for (String str : arr) {               
            if (!list.contains(str)) {
                list.add(str);
            }
        }
        list.remove(obj);
        String[] result = {};   //创建空数组
        return list.toArray(result);    //List to Array
    }
	
	@Override
	public List<Map<String, Object>>getMeunList(String menuId, String projId){
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<CheckMenusVo> overList = new ArrayList<CheckMenusVo>();
		//包含二级和三级菜单
		List<CheckMenusVo> menuList = systemMenuDao.getMenuList(menuId, projId);
		//只有最后含义评分的菜单
		List<CheckTableMenusVo> tableMenusList = systemMenuDao.getTableMenuList(menuId, projId);
		//表示存在二级菜单
		for (CheckMenusVo checkMenusVo : menuList) {
			if (checkMenusVo.getParentId().equals(menuId)) {
				overList.add(checkMenusVo);
			}
		}
		resultMap.put("overList", overList);
		resultMap.put("menuList", menuList);
		resultMap.put("result", tableMenusList);
		resultList.add(resultMap);
		return resultList;
	}
}
